//
//  PhotoBrowserController.swift
//  SinaWeiBo
//
//  Created by ZKJ on 2017/11/20.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

fileprivate let photoCell = "photoCell"

class PhotoBrowserController: UIViewController {

    // MARK:- 自定义的属性
    var indexPath : NSIndexPath
    var picUrls : [NSURL]
    
    // MARK:- 控件的属性
    fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserCollectionViewLayOut())
    fileprivate lazy var closeBtn : UIButton = UIButton(title: "关闭", titleColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), bgColor: UIColor.lightGray)
    fileprivate lazy var saveBtn : UIButton = UIButton(title: "保存", titleColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), bgColor: UIColor.lightGray)
    
    // MARK:- 自定义构造函数
    init(indexPath : NSIndexPath, picUrls : [NSURL]) {
        self.indexPath = indexPath
        self.picUrls = picUrls
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        super.loadView()
        view.frame.size.width += 20
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // MARK:- 设置UI界面
        setUpUI()
        
        //滚动到对应的图片
        collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
    }
}

extension PhotoBrowserController {
    fileprivate func setUpUI() {
        collectionView.frame = view.bounds
        collectionView.register(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoCell)
        collectionView.dataSource = self
        view.addSubview(collectionView)
        
        closeBtn.addTarget(self, action: #selector(PhotoBrowserController.closeClick), for: UIControlEvents.touchUpInside)
        view.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.leading.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        
        saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveClick), for: UIControlEvents.touchUpInside)
        view.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { (make) in
            make.trailing.equalTo(-40)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
    }
}

extension PhotoBrowserController {
    @objc fileprivate func closeClick() {
        print("取消")
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func saveClick() {
        print("保存")
        
        // 1.获取当前正在显示的image
        let cell = collectionView.visibleCells.first as! PhotoBrowserCell
        let image = cell.imgView.image
        if image != nil {
            // 2.将image对象保存相册
            UIImageWriteToSavedPhotosAlbum(image!, self, #selector(PhotoBrowserController.image(image:didFinishSavingWithError:contextInfo:)), nil)
        }
    }
    
    //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
    @objc fileprivate func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        var showMsg = ""
        if error != nil {
            showMsg = "保存失败"
        } else {
            showMsg = "保存成功"
        }
        SVProgressHUD.showInfo(withStatus: showMsg)
    }
}

extension PhotoBrowserController : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCell, for: indexPath) as! PhotoBrowserCell
        cell.picUrl = picUrls[indexPath.item]
        cell.delegate = self
        return cell
    }
}

class PhotoBrowserCollectionViewLayOut: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        itemSize = (collectionView?.frame.size)!
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

extension PhotoBrowserController : PhotoBrowserCellDelegate {
    func imageViewClick() {
        closeClick()
    }
}

// MARK:- 动画消失的代理
extension PhotoBrowserController : AnimatorDismissedDelegate {
    func indexPathForDismissView() -> NSIndexPath {
        let cell = collectionView.visibleCells.first!
        return collectionView.indexPath(for: cell)! as NSIndexPath
    }
    
    func imageViewForDismissView() -> UIImageView {
        let imageView = UIImageView()
        let cell = collectionView.visibleCells.first as! PhotoBrowserCell
        imageView.frame = cell.imgView.frame
        imageView.image = cell.imgView.image
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }
}


